###############################
### Quick Thematic Map      ###
###############################
rm(list = ls())

# fix input string errors
Sys.setlocale('LC_ALL', 'C')
options(scipen=20)

##create folder structure
##mainDir <- "C:/Users/lkaplan/Dropbox/Geocoded Aid and Conflict/Paper Geocoded Aid/graphs/maps/2019_03_20_map_data"
##mainDir <- "C:/Users/gehring/Dropbox/Geocoded Aid and Conflict/Paper Geocoded Aid/graphs/maps/2019_03_20_map_data"
mainDir <- "D:/Users/wong/Dropbox/Geocoded Aid and Conflict/Paper Geocoded Aid/graphs/maps/2019_03_20_map_confAid"

subDir <- "R_out"
if (file.exists(file.path(mainDir, subDir))){
  setwd(file.path(mainDir, subDir))
} else {
  dir.create(file.path(mainDir, subDir))
  setwd(file.path(mainDir, subDir))
}

# required
lop <- c("raster", "tmap","readstata13", "sf", "RColorBrewer", "tmaptools", "dplyr", "OpenStreetMap")
#lop <- c("raster", "foreign", , "rgdal", "rgeos", "doSNOW", "foreach", "doRNG", "doParallel", "spdep", "sp", "maptools", "reshape2", "expm")
newp <- lop[!(lop %in% installed.packages()[,"Package"])]
if(length(newp)) install.packages(newp)
lapply(lop, require, character.only = TRUE)

# devtools::install_github("mtennekes/tmap")
# require("tmap")

## zone data
grid.sf <- st_read("../../../../../Data/country_regions/gadm1_clean.shp")

## data
##dta <- read.dta13("C:/Users/lkaplan/Dropbox/Geocoded Aid and Conflict/Data/Merge/IDA_Aid_GED_ADM1.dta")
##dta <- read.dta13("C:/Users/gehring/Dropbox/Geocoded Aid and Conflict/Data/Merge/IDA_Aid_GED_ADM1.dta")
dta <- read.dta13("D:/Users/wong/Dropbox/Geocoded Aid and Conflict/Data/Merge/IDA_Aid_GED_ADM1.dta")


### get sf object for entire African countries
africa_countries <- st_read("../../../../../Data/country_regions/gadm28_adm0.shp")
africa_countries <- subset(africa_countries, UNREGION2=="Africa")
# manually set Reunion as Island
africa_countries[which((africa_countries$NAME_ENGLI=="Reunion")), which(names(africa_countries)=="Islands")] <- 1 
africa_countries <- subset(africa_countries, Islands==0)
#add Madagscar and Mauritius to sample despite being islands
isos <- c(as.character(unique(africa_countries$ISO)), "MDG", "MUS")
africa_countries$ISO <- as.character(africa_countries$ISO)


## Get sf data
gadm1 <- st_read("D:/Users/wong/Dropbox/Geocoded Aid and Conflict/Data/country_regions/gadm1_clean.shp")
gadm1_africa <- gadm1 %>% 
  subset(., ISO%in%isos) 
gadm1_africa$ISO <- as.character(gadm1_africa$ISO)

########IDA###########
## load raw aid data to plot as points
##location <- read.csv("C:/Users/gehring/Dropbox/Geocoded Aid and Conflict/Data/Aid/locations.csv")
##location <- read.csv("C:/Users/lkaplan/Dropbox/Geocoded Aid and Conflict/Data/Aid/locations.csv")
location <- read.csv("D:/Users/wong/Dropbox/Geocoded Aid and Conflict/Data/Aid/locations.csv")

##transaction <- readxl::read_xlsx("C:/Users/lkaplan/Dropbox/Geocoded Aid and Conflict/Data/Aid/IDA_IBRD_transactions.xlsx")
##transaction <- readxl::read_xlsx("C:/Users/gehring/Dropbox/Geocoded Aid and Conflict/Data/Aid/IDA_IBRD_transactions.xlsx")
transaction <- readxl::read_xlsx("D:/Users/wong/Dropbox/Geocoded Aid and Conflict/Data/Aid/IDA_IBRD_transactions.xlsx")

transaction$project_id <- transaction$projectid
transaction$projectid <- NULL
aid.df <- merge(location, transaction, by=c("project_id"))
### subset IDA data for Africa
aid.df <- subset(aid.df, financier=="IDA") 
aid.df <- subset(aid.df, precision_code<=3) 
aid.df <- subset(aid.df, grepl("Africa", aid.df$gazetteer_adm_name)==T)
aid.df<- subset(aid.df, grepl("Comoros", aid.df$gazetteer_adm_name)==F)
aid.df<- subset(aid.df, grepl("Mayotte", aid.df$gazetteer_adm_name)==F)
aid.df <- subset(aid.df, precision_code<=3)
aid.df[,"Donor"] <- "World Bank Aid" 

aid.sf <- st_as_sf(aid.df, coords = c("longitude", "latitude")) %>%
  select(year, geometry)
# ## keep only geometry and donor information
# keep <- c("geometry", "Donor")
# aid.sf <- aid.sf[,names(aid.sf) %in% keep]
########China Aid##########
#aid_china.df <- read.csv("C:/Users/lkaplan/Dropbox/Geocoded Aid and Conflict/Data/Aid_China/spatial_join_adm1_chinese_aid.csv", dec = ",", stringsAsFactors=F)
#aid_china.df <- read.csv("C:/Users/gehring/Dropbox/Geocoded Aid and Conflict/Data/Aid_China/spatial_join_adm1_chinese_aid.csv", dec = ",", stringsAsFactors=F)
aid_china.df <- read.csv("D:/Users/wong/Dropbox/Geocoded Aid and Conflict/Data/Aid_China/spatial_join_adm1_chinese_aid.csv", dec = ",", stringsAsFactors=F)

### subset IDA data for Africa
aid_china.df <- subset(aid_china.df, flow_class.C.254=="ODA-like") 
aid_china.df <- subset(aid_china.df, precision_.N.10.0<=3)
aid_china.df <- aid_china.df[aid_china.df$ISO.C.3 %in% isos,]
aid_china.df[,"Donor"] <- "Chinese Aid" 

aid_china.sf <- st_as_sf(aid_china.df, coords = c("longitude.N.19.11", "latitude.N.19.11")) %>%
  select(year_.N.10.0, geometry)





## subset data for Africa
africa.df <- subset(dta, unregion2=="Africa")
africa.df$conflict_year <- 0
africa.df$conflict_year[which(africa.df$brd_adm1>=5)] <- 1

## merge dta with sf
merge.sf <- merge(grid.sf, africa.df, by="ID_adm1")
#merge.sf$conflict_years[which(merge.sf$conflict_years==0)] <-NA

## filter out small islands
merge.sf <- merge.sf[merge.sf$ISO %in% isos,]

## subset data to make data frame smaller
map.sf <- merge.sf %>% 
  select(ID_adm1, ISO3, year, conflict_year)



## set up font family
# install.packages("extrafont")
library(extrafont)
# font_import()
# y
loadfonts()
loadfonts(device="win")

origin_cols <- c("#3A55A4", "#D4529A")
legend_colors <- c("#DCDCDC", "#FF7F00", "white")
## Create PDF and png
plot_conf_ida <- function(aid_data=NA, aid_color=NA, donor_name=NA, maplayout="nps"){
  #maplayout="esri-topo"
  ## load basemap data
  # read OSM raster data
  osm_afri <- read_osm(africa_countries, ext=1.1, type=maplayout)
  print (
    tm_shape(osm_afri) +
      tm_rgb() +
      tm_shape(africa_countries)+
      tm_borders(lwd = 2)+
      tm_shape(gadm1_africa) +
      tm_borders(col = "grey40", alpha = 0.4) +
    tm_shape(map_sub.sf) + 
      tm_polygons(c("conflict_year")
                  , alpha = 1
                  , textNA="NA"
                  , colorNA="white"
                  , palette=legend_colors[1:2]
                  , border.col = NA # border color
                  , border.alpha = 1 # transparency of border
                  , showNA=TRUE # display NA values
                  , legend.show = F
                  , title = "Conflict Event" # Title of legend,
      )  +
      # plot aid data
      tm_shape(aid_data) +
      tm_dots(col=aid_color, shape = 21, scale=4.5, border.col="black", border.lwd = 1) +
      #add legend
      tm_add_legend(type = "symbol"
                    , shape = 21
                    , col = aid_color
                    , labels = donor_name) +
      tm_add_legend(type = "fill"
                    , col = legend_colors[1:2]
                    , labels = c("No Conflict", "Conflict Incidence")) +
      tm_layout(title = t
                , legend.position = c("left", "bottom")
                , legend.text.size = 1.4
                , legend.title.size = 2.2
                , fontfamily = "Helvetica"
                , legend.width = 1.2
                , frame = F #put frame around graph?
                , legend.outside = F # legend outside of margin?
                , outer.margins = c(0, 0, 0, 0) # Relative margins between device and frame (bottom, left, top, right)
      ) 
  )
}

#### CHINESE AID
for(t in 2000:2012){
  ## subset data by year
  map_sub.sf <- subset(map.sf, year==t)
  
  aid_sub.sf <- subset(aid_china.sf, year_.N.10.0==t)
  
  png(paste0("map_confAid_china", t, ".png"))
  plot_conf_ida(aid_data=aid_sub.sf, aid_color=origin_cols[2], donor_name= "Chinese Aid Projects")
  dev.off()
}


#### WB AID
for(t in 1995:2012){
  ## subset data by year
  map_sub.sf <- subset(map.sf, year==t)
  
  aid_sub.sf <- subset(aid.sf, year==t)
  
  png(paste0("map_confAid_wb", t, ".png"))
  plot_conf_ida(aid_data=aid_sub.sf, aid_color=origin_cols[1], donor_name= "WB Aid Projects")
  dev.off()
}







# 
# 
# png(paste0("testmap.png"))
# print(
#     tm_shape(osm_afri) +
#     tm_rgb() +
#       tm_shape(africa_countries) +
#       tm_borders(lwd=2.4, col = "grey40", alpha = 0.5)
#   
# )
# dev.off()
# 
# tmap_mode("view")
# map <-   tm_shape(africa_countries) +
#   tm_borders(lwd=2.4, col = "grey40", alpha = 0.5) +
# tm_view(alpha = 1,
#         basemaps = "Esri.WorldTopoMap")
# 
# getwd()
# saveWidget( save_tmap(filename = "index.html")
# , selfcontained = F)
# 
# 
# tmap_save(tm=map,filename = "index.html")
# 
